import axios, { Axios } from "axios"
import { ElMessage } from 'element-plus'
import qs from 'qs'


const requestSerice = axios.create({
  baseURL: "/api",
  timeout: 1000 * 60 * 5
});


 
// 请求拦截器 前处理
requestSerice.interceptors.request.use(config => {
  if (!config.headers.token) {
    const token = localStorage.getItem("Authorization");
    if (token) {
      config.headers.Authorization =  `${token}`;
    }
    const proToken = localStorage.getItem("proToken");
    if(proToken){
     config.headers['proToken'] = proToken;  
    }
  }
  return config;
})


const defaultError = (state, msg) => {
  ElMessage.error({
    message : msg || '网络出了小差，请稍后再试。',
  });
  return {
    state: `${state || 'fail'}`,
    msg: msg || '网络出了小差，请稍后再试。',
  }
}

const authorityError = (state, msg) => {
  ElMessage.error({
    message : msg || '没有相关权限。',
  });
  return {
    state: `${state || 'fail'}`,
    msg: msg || '没有相关权限。',
  }
}

/**
 * 请求后处理
 */
requestSerice.interceptors.response.use(res => {
  console.log(res);
  if (res.status >= 200 &&res.status < 300) {

      if(res.data.code!=200){
        return Promise.reject(defaultError('fail',res.data.message));
      }

      return res.data

  }

  return Promise.reject(defaultError(res.status));
},
  error => {
    console.error(error);

    if(error.response.status == 403){
      return Promise.reject(authorityError(error.response.status));
    }
    return Promise.reject(defaultError(error.response.state));
  }
)




/**
 * 封装request请求  包含方法  get  post  upload文件上传
 */
const request ={
  // get: (url, params, opt) => {
  //   let config = getReqConfig(opt,'form');
  //   if (params) {
  //     config.params = params,
  //       config.paramsSerializer = params => {
  //         return qs.stringify(params, { indices: false })
  //       }
  //   }

  //   return new Promise((resolve, reject) => {
  //     requestSerice.get(url, config)
  //       .then(res => resolve(res))
  //       .catch(err => {
  //         reject(err)
  //       })
  //   })

  // },
  get: (url, params, opt) => {
    let config = getReqConfig(opt, 'form');
    console.log(config, params,opt,'config');
    if (params) {
      config.params = params;
      config.paramsSerializer = params => {
        return qs.stringify(params, { indices: false });
      };
    }

    return new Promise((resolve, reject) => {
      requestSerice.get(url, config)
        .then(res => resolve(res))
        .catch(err => {
          reject(err);
        });
    });
  },

  post: (url, data, opt) => {
    let config = getReqConfig(opt,null);
    return new Promise((resolve, reject) => {
      requestSerice.post(url,data, config)
        .then(res => resolve(res))
        .catch(err => {
          reject(err)
        })
    })
  },
  upload: (url, data, opt) => {

    console.log(data)


    return new Promise((resolve, reject) => {
      requestSerice.post(url, data, getReqConfig(opt, 'file'))
        .then(res => resolve(res))
        .catch(err => {
          reject(err)
        })
    });
  },

}


const getReqConfig = (opt, type) => {
  let _config = { headers: { 'Content-Type': 'application/json;charset=UTF-8'} ,timeout:30*1000};

  //这里没有写关于权限的内容
  if ('form' == type && typeof _config.headers != 'undefined') {
    (_config.headers)['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8';
  } else if ('file' == type && typeof _config.headers != 'undefined') {
    _config.headers['Content-Type'] = 'multipart/form-data;charset=UTF-8';
    _config.timeout = 1000 * 60 * 60; // 单位毫秒
  }
  return _config;
}


export default request;